package com.cloud.apis.attendance.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.cloud.apis.attendance.db.dao.AttendanceMapper;
import com.cloud.apis.attendance.pojo.form.*;
import com.cloud.apis.attendance.pojo.vo.CheckinVo;
import com.cloud.apis.attendance.pojo.vo.SpecialVo;
import com.cloud.apis.attendance.service.IAttendanceService;
import com.cloud.apis.core.exception.CustomException;
import com.cloud.apis.core.model.PageData;
import com.cloud.apis.core.web.R;
import com.cloud.apis.core.web.ServiceCode;
import com.cloud.apis.user.pojo.vo.UserInfoVo;
import com.cloud.apis.user.service.IUserService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Author YinXi
 * @Versin 1.0.0
 * @Date 2024/5/7
 */
@RestController
@RequestMapping("/attendance")
@Api(tags = "考勤相关API接口")
@Slf4j
public class AttendanceController {
    @Autowired
    private IAttendanceService attendanceService;
    @Autowired
    private AttendanceMapper attendanceMapper;
    @Value("${custom-config.image-folder}")
    private String imageFolder;
    public AttendanceController() {
        log.info("【AttendanceController】");
    }
    @PostMapping("/isCheckin")
    @ApiOperation("判断当前是否可以考勤签到")
    @ApiOperationSupport(order = 1)
    @SaCheckLogin
    public R isCheckin() {
        //获取当前用户id
        Long userId =  Long.parseLong((String) StpUtil.getLoginId());
        //获取当前日期
        String curDate = DateUtil.format(new Date(),"yyyy-MM-dd");
        return R.ok().put("isCheckIn",attendanceService.isCheckin(curDate,userId));
    }
    @PostMapping("/checkin")
    @ApiOperation("签到")
    @ApiOperationSupport(order = 2)
    @SaCheckLogin
    public R checkin(@Valid CheckinForm form, @RequestParam("photo") MultipartFile file)  {
        //判断上传的文件是不是空的
        if(file==null){
            return R.error("没有上传文件");
        }
        //从token中解析得到对应的userId
        Long userId = Long.parseLong((String) StpUtil.getLoginId());
        //获取文件的后缀名并且全部小写比如.jpg.png等
        String fileName = file.getOriginalFilename().toLowerCase();
        //判断上传的文件是不是.jpg的文件
        if(!fileName.endsWith(".jpg")) {
            return R.error("必须提交JPG格式图片");
        }else {
            //定义保存该.jpg文件的路径
            String path = imageFolder+"/"+fileName;
            System.out.println("checkin:"+path);
            try{
                //将文件保存在路径path中
                file.transferTo(Paths.get(path));
                //封装相关的参数
                HashMap map = new HashMap();
                map.put("userId",userId);
                map.put("path",path);
                map.put("nation",form.getNation());
                map.put("province",form.getProvince());
                map.put("city",form.getCity());
                map.put("district",form.getDistrict());
                map.put("street",form.getStreet());
                map.put("streetNumber",form.getStreetNumber());
                //实现签到
                attendanceService.checkin(map);
                return R.ok("签到成功");
            }catch (IOException e){
                log.error(e.getMessage(),e);
                throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"出错了，请稍后再尝试");
            }finally {
                //签到完成之后删除文件
                FileUtil.del(path);
            }
        }
    }

    @PostMapping("/createFaceModel")
    @ApiOperation("创建人脸模型")
    @ApiOperationSupport(order = 3)
    @SaCheckLogin
    public R createFaceModel(@RequestParam("photo")MultipartFile file){
        Long userId = Long.parseLong((String) StpUtil.getLoginId());
        if(file == null){
            return R.error("没有上传文件");
        }
        String fileName = file.getOriginalFilename().toLowerCase();
        String path = imageFolder+"/"+fileName;
        System.out.println("createFaceModel:"+path);
        if(!fileName.endsWith(".jpg")){
            return R.error("必须提交JPG格式的图片");
        }else {
            try {
                file.transferTo(Paths.get(path));
                attendanceService.createFaceModel(userId,path);
                return R.ok("创建成功");
            }catch (IOException e){
                log.error(e.getMessage());
                throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"保存图片错误");
            }
        }
    }

    @PostMapping("/specialList")
    @ApiOperation("获取特殊考勤列表")
    @ApiOperationSupport(order = 4)
    @SaCheckLogin
    public R specialList(@Valid @RequestBody SpecialListForm form){
        Integer pageNum = form.getPageNum() == null ? 1 : form.getPageNum();
        form.setPageNum(pageNum);
        PageData<SpecialVo> pageData =attendanceService.specialList(form);
        return R.ok().put("data", pageData);
    }

    @PostMapping("/specialAdd")
    @ApiOperation("添加特殊考勤")
    @ApiOperationSupport(order = 5)
    @SaCheckLogin
    public R specialAdd(@Valid @RequestBody SpecialAddForm form){
        return R.ok("添加成功").put("data",attendanceService.specialAdd(form));
    }
    @DeleteMapping("/deleteSpecialAttendance")
    @ApiOperation("删除特殊考勤")
    @ApiOperationSupport(order = 6)
    @SaCheckLogin
    public R deleteSpecialAttendance(@Valid @RequestBody DeleteSpecialAttendanceId form){
        attendanceService.deleteSpecialAttendance(form.getId());
        return R.ok("删除成功");
    }

    @PostMapping("/sys")
    @ApiOperation("批量获取打卡时间")
    @ApiOperationSupport(order = 7)
    @SaCheckLogin
    public R sys(@Valid @RequestBody SysIdsForm form){
        return R.ok().put("data",attendanceService.sys(form.getIds()));
    }

    @PutMapping("/reset")
    @ApiOperation("重置系统参数")
    @ApiOperationSupport(order = 8)
    @SaCheckLogin
    public R reset(@Valid @RequestBody SysIdsForm form){
        attendanceService.reset(form.getIds());
        return R.ok("重置成功");
    }

    @PutMapping("/setSys")
    @ApiOperation("设置系统参数")
    @ApiOperationSupport(order = 9)
    @SaCheckLogin
    public R setSys(@Valid @RequestBody SysForm form){
        System.out.println(form);
        attendanceService.setSys(form);
        return R.ok("设置成功");
    }

    @PostMapping("/getPosition")
    @ApiOperation("获取当前考勤位置")
    @ApiOperationSupport(order = 10)
    @SaCheckLogin
    public R getPosition(){
        return R.ok().put("data",attendanceService.getPosition());
    }

    @PutMapping("/resetPosition")
    @ApiOperation("重置考勤位置")
    @ApiOperationSupport(order = 11)
    @SaCheckLogin
    public R resetPosition(@Valid @RequestBody ResetPositionForm form){
        attendanceService.resetPosition(form);
        return R.ok("重置成功");
    }

    @PostMapping("/searchMonthCheckin")
    @ApiOperation("查询当前用户某月签到数据")
    @ApiOperationSupport(order = 12)
    @SaCheckLogin
    public R searchMonthCheckin(@Valid @RequestBody SearchMonthCheckinForm form){
        long userId = 0L;
        if(form.getUserId()==null){
            //获取用户的id
            userId = Long.parseLong((String) StpUtil.getLoginId());
        }else {
            userId = form.getUserId();
        }
        ArrayList<HashMap> list = attendanceService.searchMonthCheckin(userId,form.getYear(),form.getMonth());
        int sum_1=0,sum_2=0,sum_3=0;
        for (HashMap<String,String> one:list){
            //判断当前是休息日还是工作日
            String type = one.get("type");
            String status = one.get("status");
            if("工作日".equals(type)){
                if ("正常".equals(status)){
                    sum_1++;
                }else if("迟到".equals(status)){
                    sum_2++;
                }else if ("缺勤".equals(status)){
                    sum_3++;
                }
            }
        }
        return R.ok().put("list",list).put("sum_1",sum_1).put("sum_2",sum_2).put("sum_3",sum_3);
    }

    @GetMapping("/searchTodayCheckin")
    @ApiOperation("查询用户当日前签到数据")
    @ApiOperationSupport(order = 13)
    @SaCheckLogin
    public R searchTodayCheckin(){
        Long userId = Long.parseLong((String) StpUtil.getLoginId());
        HashMap map = attendanceService.searchTodayCheckin(userId);
        map.put("attendanceTime",attendanceMapper.selectByParamKey("attendance_time"));
        map.put("closingTime",attendanceMapper.selectByParamKey("closing_time"));
        long days = attendanceService.searchCheckinDays(userId);
        map.put("checkinDays",days);
        ArrayList<HashMap> list = attendanceService.weekCheckin(userId);
        map.put("weekCheckin",list);
        return R.ok().put("result",map);
    }
}
